<?php
/**
 * Middleware   系统核心-中间件
 * @copyright   Copyright(c) 2024-2034
 * @author      tianjie <527707665@qq.com>
 * @link        http://www.tinphp.com/
 * @version     4.1
 */

namespace tian;

use RuntimeException;

class Middleware
{
    protected static $instances = [];

    /**
     * 加载中间件
     * @param $allMiddlewares
     * @param string $plugin
     * @return void
     */
    public static function load($allMiddlewares, string $plugin = '')
    {
        if (!is_array($allMiddlewares)) {
            return;
        }
        foreach ($allMiddlewares as $appName => $middlewares) {
            if (!is_array($middlewares)) {
                throw new RuntimeException('Bad middleware config');
            }
            if ($appName === '@') {
                $plugin = '';
            }

            foreach ($middlewares as $className) {
                if (method_exists($className, 'handle')) {
                    if(empty($plugin)){
                        static::$instances[$appName][] = [$className, 'handle'];
                    }else{
                        static::$instances[$plugin][$appName][] = [$className, 'handle'];
                    }

                } else {
                    // @todo Log
                    exit("middleware $className::handle not exsits\n");
                }
            }
        }
    }

    /**
     * @param string $plugin
     * @return array
     */
    public static function getMiddleware(string $plugin = ''): array
    {
        //全局中间件
        $globalMiddleware = empty($plugin) ? static::$instances[''] ?? [] : [];
        //应用中间件
        $appGlobalMiddleware = $plugin && isset(static::$instances[$plugin]) ? static::$instances[$plugin] : [];

        return array_reverse(array_merge($globalMiddleware, $appGlobalMiddleware));
    }

}
